package com.elias.share.task;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.unit.DataSizeUtil;
import cn.hutool.core.lang.Assert;
import com.elias.share.config.bean.FileInfo;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.unit.DataSize;

import javax.annotation.Resource;
import java.io.File;
import java.nio.file.Files;

@Log4j2
@Component
public class InnitRunner implements ApplicationRunner {

    @Resource
    private FileInfo fileInfo;

    @Override
    public void run(ApplicationArguments args) {
        try {
            assertData();
            String location = fileInfo.getLocation();
            File file = new File(location);
            if (file.exists()) {
                if (file.isFile()) {
                    log.error("file location is not a directory,exit");
                    System.exit(1);
                }
                if (!file.canRead() || !file.canWrite()) {
                    log.error("the program not has the dir permission,exit");
                    System.exit(1);
                }
                long fileSize = FileUtil.size(file);
                fileInfo.setUsedSize(DataSize.ofBytes(fileSize));
                log.info("th directory has used size: " + DataSizeUtil.format(fileSize));
            } else {
                log.error("file location is not exist,try to make dir");
                boolean mkdirs = file.mkdirs();
                if (!mkdirs) {
                    log.error("make dir error,exit");
                    System.exit(1);
                }
                fileInfo.setUsedSize(DataSize.ofBytes(FileUtil.size(file)));
            }
            log.info("FileInfo initialized success,info:{}", fileInfo);
        } catch (Exception e) {
            log.error(e);
            System.exit(1);
        }
    }

    private void assertData() {
        Assert.notBlank(fileInfo.getLocation());
        Assert.notNull(fileInfo.getMaxSize());
        Assert.notNull(fileInfo.getMaxExpireTime());
        Assert.isTrue(fileInfo.getMinExpireTime().compareTo(10) >= 0 &&
                fileInfo.getMaxExpireTime().compareTo(fileInfo.getMinExpireTime()) > 0);
    }

}

